package com.qsl.stock.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qsl.stock.entity.WareStock;
import com.qsl.stock.mapper.WareStockMapper;
import com.qsl.stock.service.WareStockService;
import com.qsl.stock.vo.WareStockVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;

/***
 * @description ware stock service
 * @author 青石路
 * @date 2022/1/9 18:50
 */
@Service
public class WareStockServiceImpl extends ServiceImpl<WareStockMapper, WareStock> implements WareStockService {

    @Override
    public WareStockVo get(Long stockId) {
        WareStock wareStock = getById(stockId);
        if (Objects.isNull(wareStock)) {
            return null;
        }
        WareStockVo wareStockVo = new WareStockVo();
        BeanUtils.copyProperties(wareStock, wareStockVo);
        return wareStockVo;
    }

    @Override
    public boolean deduct(Long wareId, BigDecimal deductQty) {
        LambdaUpdateWrapper<WareStock> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(WareStock::getWareId, wareId)
                .setSql("qualified_qty=qualified_qty-" + deductQty);
        boolean update = this.update(updateWrapper);
        if (!update) {
            throw new RuntimeException("库存不足");
        }
        return true;
    }
}
